Serialize data classes based on their fields only #2697
Closed
+21
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary:
Context:
I think the unit test is the easiest way to understand this!
There are several cases in Ax where an instance has an attribute that
torch.nn.Module
, including BoTorch models, but can be other large and complex objects,These classes have thus required custom serialization logic so that such attributes are not serialized. Classes that have this issue include many benchmarking classes that work with surrogates or neural nets, such as
SurrogateRunner
,PyTorchCNNTorchvisionRunner
, andPyTorchCNNTorchvisionBenchmarkProblem
, as well as MBM classes.A simpler solution is to use dataclasses, by
InitVar
, and, if they are needed immediately, constructing them in the__post_init__
InitVar
s are not fieldsThis gives more flexibility in what we serialize without taking any away: If an attribute is constructed in the post-init and should be serialized, that is still supported by marking it as a
field
and not anInitVar
. Attributes that are constructed in the init will be serialized, even if they are modified elsewhere.Downside
It is not quite the normal usage to use an
InitVar
to define a persistent non-field attribute; insteadInitVar
is intended for something that is needed only for initializing fields. So the usage pattern outlined in the unit test causes Pyre errors, and someone who uses anInitVar
that way might be surprised that it can't be recovered. However, it might not need to be, since the other fields would be recovered. Also,InitVar
is a rarely used feature.This PR:
Differential Revision: D61665461